import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef, useState } from 'react'
import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent, TitleComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

import { CustomRingChartWarpper } from './style'

import { calcZoomAndScale } from "@/utils"

echarts.use([
    TooltipComponent,
    LegendComponent,
    TitleComponent,
    PieChart,
    CanvasRenderer,
    LabelLayout
]);

const index = memo((props) => {
    const [zoom, setZoom] = useState()
    const [scale, setScale] = useState()
    const { height = "120px", data = [], chartSeries = {} } = props
    const elRef = useRef()
    useEffect(() => {
        let myChart = echarts.init(elRef.current);
        function chartResize() {
            const { _zoom, _scale } = calcZoomAndScale()
            setScale(_scale)
            setZoom(_zoom)
        }
        function initChart() {
            const option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    icon: "circle",
                    textStyle: {
                        color: '#fff',
                        fontSize: 15
                    },
                },
                series: [
                    {
                        name: '',
                        type: 'pie',
                        radius: ['52%', '65%'],
                        label: {
                            show: false,
                            position: 'center'
                        },
                        data: data
                    }
                ]
            };
            option && myChart.setOption(option);
            chartSeries && myChart.setOption(chartSeries);
            chartResize()
        }
        initChart()
        window.addEventListener("resize", chartResize)
        return () => {
            window.removeEventListener("resize", chartResize)
        }
    }, [])
    return (
        <CustomRingChartWarpper height={height}>
            <div ref={elRef} className="chart-container" style={{ zoom: zoom, transform: "scale(" + scale + ")", transformOrigin: '0 0' }}></div>
        </CustomRingChartWarpper>
    )
})

index.propTypes = {
    height: PropTypes.string,
    data: PropTypes.array,
    chartSeries: PropTypes.object
}

export default index